package cloud.pangui.core.utils;

import cloud.pangui.core.exception.UtilsRuntimeException;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Auther hepangui
 * @Date 2020/11/5 0005
 */
public class MD5Utils {

	public static final String DEFAULT_CHARTSET = "UTF-8";

	/**
	 * 字符串md5 ，UTF-8
	 * @param content
	 * @return
	 */
	public static String md5(String content) {
		return md5(content, DEFAULT_CHARTSET);
	}

	/**
	 * 指定charset的md5
	 * @param content
	 * @param charset
	 * @return
	 */
	public static String md5(String content, String charset) {
		try {
			return md5(content.getBytes(charset));
		} catch (UnsupportedEncodingException e) {
			throw new UtilsRuntimeException(e);
		}
	}

	/**
	 * 文件md5
	 * @param file
	 * @return
	 */
	public static String md5(File file) {

		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			MessageDigest m = MessageDigest.getInstance("MD5");
			byte[] buffer = new byte[8192];
			int length;
			while ((length = fileInputStream.read(buffer)) != -1) {
				m.update(buffer, 0, length);
			}
			return toHex(m.digest());
		} catch (Exception e) {
			throw new UtilsRuntimeException(e);
		}
	}

	/**
	 * byte进行md5
	 * @param bytes
	 * @return
	 */
	public static String md5(byte[] bytes) {
		try {
			MessageDigest m = MessageDigest.getInstance("MD5");
			m.update(bytes);
			byte[] s = m.digest();
			return toHex(s);
		} catch (NoSuchAlgorithmException e) {
			throw new UtilsRuntimeException(e);
		}
	}


	public static String toHex(byte[] bytes) {
		StringBuilder sb = new StringBuilder();
		byte[] var2 = bytes;
		int var3 = bytes.length;

		for (int var4 = 0; var4 < var3; ++var4) {
			byte b = var2[var4];
			String s = Integer.toHexString(255 & b);
			if (s.length() < 2) {
				sb.append("0");
			}

			sb.append(s);
		}

		return sb.toString();
	}
}

